#include <set>

#include "JsonReader.h"
#include "INode.h"
#include "Registry.h"
#include "ActorTable.h"
#include "Scene.h"

void JsonReader::buildRelations()
{
	Registry &reg = Registry::instance();
	auto scene = reg.get<Scene>(constructSceneID);

	for (const auto& builder : builders)
	{
		builder(this, scene);
	}
}

void JsonReader::pushIDBuilder(int & id)
{
	if (id > 0)
	{
		IdBuilder builder;
		builder.pId = &id;
		builders.push_back(builder);
	}
}

void JsonReader::pushIDVectorBuilder(std::vector<int>& ids)
{
	IdVectorBuilder builder;
	builder.pIds = &ids;
	builders.push_back(builder);
}

void JsonReader::pushIDSetBuilder(std::set<int>& ids)
{
	IdSetBuilder builder;
	builder.pIds = &ids;
	builders.push_back(builder);
}

void IdBuilder::operator()(JsonReader * pReader, Scene * scene)
{
	*pId = pReader->idMap[*pId];
}

void IdVectorBuilder::operator()(JsonReader * pReader, Scene * scene)
{
	auto& ids = *pIds;
	for (int i = 0; i < ids.size(); ++i)
	{
		if (ids[i] > 0)
			ids[i] = pReader->idMap[ids[i]];
	}
}

void IdSetBuilder::operator()(JsonReader * pReader, Scene * scene)
{
	std::set<int> newIDs;
	for (int id: *pIds)
	{
		if (id > 0)
			newIDs.insert(pReader->idMap[id]);
		else
			newIDs.insert(id);
	}
	*pIds = newIDs;
}
